//
//  QRCodeViewController.swift
//  CXCWeibo
//
//  Created by cxc on 15/6/29.
//  Copyright © 2015年 china. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController,UITabBarDelegate,AVCaptureMetadataOutputObjectsDelegate {

    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    @IBOutlet weak var scanImage: UIView!
    @IBOutlet weak var resultLaber: UILabel!
    @IBOutlet weak var tabBar: UITabBar!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        tabBar.selectedItem = tabBar.items![0]
        tabBar.delegate = self
        
        //设置二维码扫描环境
        setupSession()
        setupLayers()
        
    }

    @IBAction func showMyCord(sender: AnyObject) {
        navigationController?.pushViewController(QRCodeMyCardViewController(), animated: true)
        
    }

    @IBAction func close(sender: AnyObject) {
        dismissViewControllerAnimated(true,completion:nil)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        startAnimation()
        startScan()
    }
    
    func startAnimation(){
        topConstraint.constant = -heightConstraint.constant
        self.view.layoutIfNeeded()
        
        UIView.animateWithDuration(2.0) { () -> Void in
            /**
            *  重复次数需要放到内部
            */
            UIView.setAnimationRepeatCount(MAXFLOAT)
            
            self.topConstraint.constant = self.heightConstraint.constant
            self.view.layoutIfNeeded()
        }
    }
    // MARK: - tabBar代理方法
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        heightConstraint.constant = widthConstraint.constant * (item.tag == 1 ? 0.5 : 1)
        
        scanImage.layer.removeAllAnimations()
        startAnimation()
    }
    
    // MARK: - 二维码扫描
    func startScan(){
        session.startRunning()
    }
    
    /**
    设置图层
    */
    private func setupLayers(){
        drawLayer.frame = view.bounds
        view.layer.insertSublayer(drawLayer, atIndex: 0)
        
        previewLayer.frame = view.bounds
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        view.layer.insertSublayer(previewLayer, atIndex: 0)
    }
    
    // 设置会话
    private func setupSession(){
        if !session.canAddInput(inputDevice){
            print("无法添加输入设备")
            return
        }
        if !session.canAddOutput(ouputData){
            print("无法添加输出数据")
            return
        }
        //添加设备
        session.addInput(inputDevice)
        print("前 \(ouputData.availableMetadataObjectTypes)")
        session.addOutput(ouputData)
        print("后 \(ouputData.availableMetadataObjectTypes)")
        
        //设置数据的检查类型,检查所有支持的数据格式
        ouputData.metadataObjectTypes = ouputData.availableMetadataObjectTypes
        
        ouputData.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        
    }
    
    // MARK: - AVCaptureMetadataOutputObjectsDelegate
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        clearDrawLayer()
        
        for object in metadataObjects{
            //判断识别对象类型
            if object is AVMetadataMachineReadableCodeObject{
                let codeObject = previewLayer.transformedMetadataObjectForMetadataObject(object as!AVMetadataObject) as! AVMetadataMachineReadableCodeObject
                
                drawCorners(codeObject)
                resultLaber.text = codeObject.stringValue
                resultLaber.sizeToFit()
            }
        }
    }
    //清空绘图图层
    private func clearDrawLayer(){
        if drawLayer.sublayers == nil{
            return
        }
        for sublayer in drawLayer.sublayers!{
            sublayer.removeFromSuperlayer()
        }
    }
    
    /**绘制一个变形图形*/
    private func drawCorners(codeObject:AVMetadataMachineReadableCodeObject){
        print(codeObject)
        //可以做动画绘图，专门在图层上画图
        let layer = CAShapeLayer()
        layer.lineWidth = 4
        layer.strokeColor = UIColor.greenColor().CGColor
        layer.fillColor = UIColor.clearColor().CGColor
        
        layer.path = createPath(codeObject.corners).CGPath
        drawLayer.addSublayer(layer)
    }
    
    /**返回一个完整的路径*/
    private func createPath(corners:NSArray) -> UIBezierPath{
        let path = UIBezierPath()
        var point = CGPoint()
        var index = 0
        CGPointMakeWithDictionaryRepresentation(corners[index++] as! CFDictionary, &point)
        path.moveToPoint(point)
        
        /// 遍历剩余的点
        while index < corners.count{
            CGPointMakeWithDictionaryRepresentation(corners[index++] as! CFDictionary, &point)
            path .addLineToPoint(point)
        }
        path.closePath()
        
        return path
    }
    // MARK: - 懒加载
    /**
    *  绘图图层
    */
    lazy var drawLayer:CALayer = CALayer()
    /**
    *  预览视图
    */
    lazy var previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)
    /// session桥梁
    lazy var session:AVCaptureSession = AVCaptureSession()
 
    // 输入设备
    lazy var inputDevice: AVCaptureDeviceInput? = {
        // 取摄像头设备
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        
        do {
            return try AVCaptureDeviceInput(device: device)
        } catch {
            print(error)
            return nil
        }
        }()
    /**
    *  输出设备
    */
    lazy var ouputData:AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
}
